package com.snowfield.lb47.utils;

import com.alibaba.fastjson2.JSONObject;
import com.ruoyi.common.core.redis.RedisCache;
import com.ruoyi.common.utils.StringUtils;
import com.ruoyi.common.utils.spring.SpringUtils;
import com.snowfield.lb47.lbconfig.domain.Backserver;

import java.util.Collection;
import java.util.List;
import java.util.Map;

public class BackserverCache {
    private static final String BACKSERVER_KEY = "backserver:";
    private static final String BACKSERVER_SUMMARY_KEY = "backserverSummary";

    /**
     * 设置后端服务器缓存
     *
     * @param serverList 后端服务器列表
     */
    public static void setServerCache(List<Backserver> serverList) {
        for (Backserver server : serverList) {
            Long serverId = server.getId();
            SpringUtils.getBean(RedisCache.class).setCacheObject(getCacheKey(String.valueOf(serverId)), server);
        }
    }

    /**
     * 设置后端服务器缓存
     *
     * @param key    键
     * @param server 后端服务器
     */
    public static void setServerCache(String key, Backserver server) {
        SpringUtils.getBean(RedisCache.class).setCacheObject(getCacheKey(key), server);
    }

    /**
     * 获取后端服务器缓存
     *
     * @param key 键
     * @return objectCache 后端服务器
     */
    public static JSONObject getServerCache(String key) {
        JSONObject objectCache = SpringUtils.getBean(RedisCache.class).getCacheObject(getCacheKey(key));
        if (StringUtils.isNotNull(objectCache)) {
            return objectCache;
        }
        return null;
    }

    /**
     * 删除指定后端服务器缓存
     *
     * @param key 键
     */
    public static void removeServerCache(String key) {
        SpringUtils.getBean(RedisCache.class).deleteObject(getCacheKey(key));
    }

    /**
     * 清空后端服务器缓存
     */
    public static void clearServerCache() {
        Collection<String> keys = SpringUtils.getBean(RedisCache.class).keys(BACKSERVER_KEY + "*");
        SpringUtils.getBean(RedisCache.class).deleteObject(keys);
    }

    /**
     * 设置cache key
     *
     * @param key 键
     * @return 缓存键key
     */
    public static String getCacheKey(String key) {
        return BACKSERVER_KEY + key;
    }

    /**
     * 设置全部后端服务器概要信息缓存
     *
     * @param serverSummary 全部后端服务器概要信息
     */
    public static void setServerSummaryCache(Map<String, Map<String,String>> serverSummary) {
        SpringUtils.getBean(RedisCache.class).setCacheMap(BACKSERVER_SUMMARY_KEY, serverSummary);
    }

    /**
     * 获取全部后端服务器概要信息缓存
     *
     */
    public static Map<String, Map<String,String>> getServerSummaryCache() {
        Map<String, Map<String,String>> objectCache = SpringUtils.getBean(RedisCache.class).getCacheMap(BACKSERVER_SUMMARY_KEY);
        if (StringUtils.isNotNull(objectCache)) {
            return objectCache;
        }
        return null;
    }

    /**
     * 删除全部后端服务器概要信息缓存
     *
     */
    public static void removeServerSummaryCache() {
        SpringUtils.getBean(RedisCache.class).deleteObject(BACKSERVER_SUMMARY_KEY);
    }
}
